# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os

from django.http import HttpResponse, FileResponse
from rest_framework.views import APIView

from main import settings
from utils.views import Result



def read_file(url, chunk_size=512):
        with open(url, "rb") as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

class TmpFileDown(APIView):
    def post(self, request):
        data = request.data
        file_type = data['file_type']
        file_name = data['file_name']
        local_file_path = os.path.join(settings.APP_CONF['TMPPATH'], file_type, file_name)

        try:
            response = HttpResponse(read_file(local_file_path))
            response['content_type'] = "application/octet-stream"
            response['Content-Disposition'] = 'attachment; filename=' + file_name
            return response

        except Exception as e:
            Result.fail_response(data=[], msg='下载失败(%s)' %e)
